package com.jxsd.edu.cn.tools;

import java.util.HashMap;

import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import com.jxsd.edu.cn.tools.ParseTool;


/**
 * 爬取特定的书籍信息
 * */
public class BookInfoCrawler   
{
    private  HashMap<String,String>  map;
	
	public HashMap<String,String> crawling(String url)
	{
  		Example  e=new  Example();
  		String   inputHTML=e.getHtml(url);
  		getAttribute(inputHTML);
  		getTitle(inputHTML);
  		getContent(inputHTML);
  	
  		return  map;
	}
	
	private  void  getTitle(String  inputHTML)
	{
		Parser   parse=new  Parser();
  		try 
  		{
 			parse.setInputHTML(inputHTML);
 			NodeFilter   filter=new   HasAttributeFilter("class","goods_title");
 			NodeList      nodes=parse.extractAllNodesThatMatch(filter);
 			if(nodes!=null)
 			{
 				Node  node=nodes.elementAt(0);
 				String  text=node.getFirstChild().toPlainTextString();
 				map.put("书名", text);
 			}
 			
 		} catch (ParserException e1)
 		{
 			e1.printStackTrace();
 		}
	}
	
	private  void  getAttribute(String  inputHTML)
	{
		 Parser   parse=new  Parser();
	   		
	   		try 
	   		{
	  			parse.setInputHTML(inputHTML);
	  			
	  			NodeFilter   filter=new   HasAttributeFilter("class","ohter_info");
	  			NodeList      nodes=parse.extractAllNodesThatMatch(filter);
	  			if(nodes!=null)
	  			{
	  				Node  textnode=nodes.elementAt(0);
	  				
	  				if(textnode==null)
	  				{
	  					System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%#########################");
	  					System.out.println("textnode为空1");
	  					System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%#########################");
	  				}
	  				String  str=ParseTool.trimer(textnode.toPlainTextString());
	  				map=ParseTool.getAttributes(str);
	  			}
	  			
	  		} catch (ParserException e1)
	  		{
	  			e1.printStackTrace();
	  		} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	
	private  void  getContent(String  inputHTML)
	{
		Parser   parse=new  Parser();
 		
 		try 
 		{
			parse.setInputHTML(inputHTML);
			
			NodeFilter   filter=new  TagNameFilter("PRE");
			NodeList      nodes=parse.extractAllNodesThatMatch(filter);
			if(nodes!=null)
			{
				Node  node=nodes.elementAt(1);
				Node  textnode=node.getNextSibling(); 
				
				String s=ParseTool.insertEnter(ParseTool.trimer(textnode.getText()));
				map.put("describes", s);
			}
			
		} catch (ParserException e1)
		{
			e1.printStackTrace();
		}
     }
	
}
